<template>
  <div>
    <el-page-header content="教练排班表管理">
      <template #extra>
        <div class="page-header-extra">
          <el-input
            v-model="searchQuery"
            placeholder="搜索教练姓名"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="fetchSchedules"
          />
          <el-button type="primary" @click="addDialogVisible = true">增加排班</el-button>
        </div>
      </template>
    </el-page-header>

    <el-table :data="filteredSchedules" style="width: 100%">
      <el-table-column label="序号" width="80">
                    <template #default="scope">
                        {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                    </template>
      </el-table-column>
      <el-table-column label="教练姓名">
        <template #default="scope">
          {{ getCoachName(scope.row.coach_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="day_of_week" label="星期">
        <template #default="scope">
          {{ getDayOfWeekLabel(scope.row.day_of_week) }}
        </template>
      </el-table-column>
      <el-table-column prop="start_time" label="开始时间">
        <template #default="scope">
          {{ formatTime(scope.row.start_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="end_time" label="结束时间">
        <template #default="scope">
          {{ formatTime(scope.row.end_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="is_active" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
            {{ scope.row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <div class="operation-cell">
            <el-button size="small" type="primary" @click="editSchedule(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteSchedule(scope.row.schedule_id)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增排班对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增排班" width="50%">
      <el-form :model="addForm" label-width="120px" ref="addFormRef" :rules="formRules">
        <el-form-item label="教练" prop="coach_id">
          <el-select v-model="addForm.coach_id" placeholder="请选择教练" style="width: 100%">
            <el-option
              v-for="coach in coaches"
              :key="coach.coach_id"
              :label="coach.fullname"
              :value="coach.coach_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="星期" prop="day_of_week">
          <el-select v-model="addForm.day_of_week" placeholder="请选择星期" style="width: 100%">
            <el-option
              v-for="(label, value) in dayOfWeekOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="start_time">
          <el-time-picker
            v-model="addForm.start_time"
            value-format="HH:mm:ss"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="end_time">
          <el-time-picker
            v-model="addForm.end_time"
            value-format="HH:mm:ss"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="是否启用" prop="is_active">
          <el-switch
            v-model="addForm.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑排班对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑排班信息" width="50%">
      <el-form :model="editForm" label-width="120px" ref="editFormRef" :rules="formRules">
        <el-form-item label="排班ID">
          <el-input v-model="editForm.schedule_id" disabled />
        </el-form-item>

        <el-form-item label="教练" prop="coach_id">
          <el-select v-model="editForm.coach_id" placeholder="请选择教练" style="width: 100%">
            <el-option
              v-for="coach in coaches"
              :key="coach.coach_id"
              :label="coach.fullname"
              :value="coach.coach_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="星期" prop="day_of_week">
          <el-select v-model="editForm.day_of_week" placeholder="请选择星期" style="width: 100%">
            <el-option
              v-for="(label, value) in dayOfWeekOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="start_time">
          <el-time-picker
            v-model="editForm.start_time"
            value-format="HH:mm:ss"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="end_time">
          <el-time-picker
            v-model="editForm.end_time"
            value-format="HH:mm:ss"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="是否启用" prop="is_active">
          <el-switch
            v-model="editForm.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="displayTotal"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import requestUtil from '@/util/request.js'

const schedules = ref([])
const allSchedules = ref([]) // 存储所有排班数据用于前端过滤
const coaches = ref([]) // 教练列表

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索字段
const searchQuery = ref('')

// 添加表单
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = ref({
  coach_id: null,
  day_of_week: '',
  start_time: '',
  end_time: '',
  is_active: true
})

// 编辑表单
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = ref({
  schedule_id: null,
  coach_id: null,
  day_of_week: '',
  start_time: '',
  end_time: '',
  is_active: true
})

// 星期选项
const dayOfWeekOptions = {
  '1': '周一',
  '2': '周二',
  '3': '周三',
  '4': '周四',
  '5': '周五',
  '6': '周六',
  '7': '周日'
}

// 获取星期标签
const getDayOfWeekLabel = (dayOfWeek) => {
  return dayOfWeekOptions[dayOfWeek] || dayOfWeek
}

// 根据教练ID获取教练姓名
const getCoachName = (coachId) => {
  const coach = coaches.value.find(coach => coach.coach_id === coachId)
  return coach ? coach.fullname : '未知教练'
}

// 时间格式化函数
const formatTime = (time) => {
  if (!time) return ''

  // 如果是字符串格式的时间 HH:mm:ss
  if (typeof time === 'string' && time.includes(':')) {
    return time
  }

  // 如果是秒数格式（浮点数或整数）
  if (typeof time === 'number' || !isNaN(parseFloat(time))) {
    const totalSeconds = Math.floor(typeof time === 'string' ? parseFloat(time) : time)
    const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
    const minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0')
    const seconds = String(totalSeconds % 60).padStart(2, '0')
    return `${hours}:${minutes}:${seconds}`
  }

  return time
}

// 修改分页显示的总数
const displayTotal = computed(() => {
  return searchQuery.value ? filteredSchedules.value.length : total.value
})

// 表单验证规则
const formRules = {
  coach_id: [
    { required: true, message: '请选择教练', trigger: 'change' }
  ],
  day_of_week: [
    { required: true, message: '请选择星期', trigger: 'change' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 计算属性实现前端过滤
const filteredSchedules = computed(() => {
  if (!searchQuery.value) {
    return schedules.value
  }

  const query = searchQuery.value.toLowerCase()
  return allSchedules.value.filter(schedule => {
    const coachName = getCoachName(schedule.coach_id)
    return (
      coachName.toLowerCase().includes(query) ||
      (schedule.day_of_week && getDayOfWeekLabel(schedule.day_of_week).includes(query))
    )
  })
})

/**
 * 每页条数变化
 */
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchSchedules()
}

/**
 * 当前页码变化
 */
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchSchedules()
}

// 获取排班列表
const fetchSchedules = async () => {
  try {
    // 先获取教练列表，因为排班需要关联教练信息
    await fetchCoaches()

    const response = await requestUtil.get('/schedule/msg', {
        page: currentPage.value,
        page_size: pageSize.value
    })

    // 处理返回的数据，确保时间格式正确
    const scheduleData = response.data.data || []
    schedules.value = scheduleData.map(schedule => {
      return {
        ...schedule,
        start_time: schedule.start_time,
        end_time: schedule.end_time
      }
    })

    allSchedules.value = schedules.value
    total.value = response.data.total || 0
  } catch (error) {
    console.error('获取排班列表失败:', error)
    ElMessage.error('获取排班列表失败')
  }
}

// 获取教练列表
const fetchCoaches = async () => {
  try {
    // 尝试不带分页参数的请求
    const response = await requestUtil.get('/coach/msg')
    coaches.value = response.data.data || response.data || []
  } catch (error) {
    console.error('获取教练列表失败:', error)
    // 如果不带参数也失败，尝试使用 params 方式传递参数
    try {
      const response = await requestUtil.get('/coach/msg', {
          page: 1,
          page_size: 1000
      })
      coaches.value = response.data.data || response.data || []
    } catch (secondError) {
      console.error('获取教练列表仍然失败:', secondError)
      ElMessage.error('获取教练列表失败')
    }
  }
}

// 编辑排班
const editSchedule = async (row) => {
  editForm.value = {
    ...row,
    start_time: formatTime(row.start_time),
    end_time: formatTime(row.end_time)
  }
  editDialogVisible.value = true
}

// 提交新增表单
const submitAddForm = async () => {
  try {
    const valid = await addFormRef.value.validate()
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }

    // 格式化时间后再提交
    const formData = {
      ...addForm.value,
      start_time: addForm.value.start_time,
      end_time: addForm.value.end_time
    }

    await requestUtil.post('/schedule/add', formData)
    addDialogVisible.value = false
    ElMessage.success('新增成功')
    await fetchSchedules()
  } catch (error) {
    console.error('新增失败:', error)
    ElMessage.error(`新增失败: ${error.response?.data?.message || error.message}`)
  }
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    const valid = await editFormRef.value.validate()
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }

    // 格式化时间后再提交
    const formData = {
      ...editForm.value,
      start_time: editForm.value.start_time,
      end_time: editForm.value.end_time
    }

    await requestUtil.put(
      `/schedule/update/${editForm.value.schedule_id}`,
      formData
    )
    editDialogVisible.value = false
    ElMessage.success('更新成功')
    await fetchSchedules()
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error(`更新失败: ${error.response?.data?.message || error.message}`)
  }
}

// 删除排班
const deleteSchedule = async (id) => {
  try {
    // 添加确认提示
    await ElMessageBox.confirm(
      '确定要删除这个排班吗？此操作不可恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await requestUtil.del(`/schedule/delete/${id}`)
    if (response.data.status === 200) {
      ElMessage.success('删除成功')
      await fetchSchedules()
    } else {
      ElMessage.error('删除失败: ' + response.data.message)
    }
  } catch (error) {
    // 用户取消删除操作
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消删除')
      return
    }

    console.error('删除排班失败:', error)
    ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
  }
}

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1
  fetchSchedules()
}

const handleSearchClear = () => {
  searchQuery.value = ''
  currentPage.value = 1
  fetchSchedules()
}

onMounted(() => {
  fetchSchedules()
})
</script>

<style scoped>
.operation-cell .el-button {
  margin-right: 8px;
}

.operation-cell .el-button:last-child {
  margin-right: 0;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.page-header-extra {
  display: flex;
  align-items: center;
}
</style>
